
const utils = require('../../utils/util.js');

Page({
  data: {
    searchContent: '',
    songs: []
  },

  setSearchKey(e) {
    this.setData({
      searchContent: e.detail.value
    });
  },

  searchFromButton() {
    const searchContent = this.data.searchContent;
    if (!searchContent) {
      wx.showToast({
        title: '请输入关键词',
        icon: 'none'
      });
      return;
    }
    
    // 发起API请求
    wx.request({
      url: `http://localhost:3200/getSearchByKey?key=${searchContent}`,
      success: res => {
        console.log("获取成功:", res); // 打印整个响应对象
        if (res.data.response.code === 0) {
          const songList = res.data.response.data.song.list;
          const songs = songList.map(item => ({
            songName: item.songname,
            artist: item.singer.map(s => s.name).join(', '),
            songmid:item.songmid
          }));
          this.setData({
            songs
          });
          // 将数据缓存到本地
          wx.setStorageSync('songs', songs);
          console.log("设置数据成功:", songs); // 打印设置的数据
        } else {
          wx.showToast({
            title: '搜索失败，请重试',
            icon: 'none'
          });
          console.error("搜索失败，返回的code:", res.data.response.code); // 打印错误的code
        }
      },
      fail: err => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
        console.error("网络请求失败:", err); // 打印错误信息
      }
    });
  },

  pickMusic(e) {
    const song = e.currentTarget.dataset.data;
    wx.setStorageSync('currentsong', song)
    console.log('选择了歌曲：', song);
  },

  getMoreSongs() {
    // 实现加载更多歌曲的逻辑
  },

  //添加至歌单
  PlayListAdd: function(e) {
    let id = e.currentTarget.dataset.sId;
    console.log(id);
    let selectedSong = this.data.songs.find(item => item.songmid === id);
    
    if (selectedSong) {
        if (!selectedSong.isAdded) {
            utils.addToPlaylist(selectedSong.songmid);
            console.log("添加成功");

            let AllsongsFromStorage = wx.getStorageSync('songs') || [];
            let selectedInAll = AllsongsFromStorage.find(item => item.songmid === selectedSong.songmid);
            selectedInAll.isAdded = true;

            let PlayList = wx.getStorageSync('MusicFromData') || [];
            // 检查PlayList中是否已经存在该歌曲
            let isSongInPlayList = PlayList.some(item => item.songmid === selectedSong.songmid);
            if (!isSongInPlayList) {
                PlayList.push(selectedInAll);
                wx.setStorageSync('MusicFromData', PlayList);
            } else {
                console.log("歌曲已存在歌单中");
            }

            // 确保 currentsong 和 RoomId 存在且数据完整
            let song = wx.getStorageSync('currentsong');
            let roomId = wx.getStorageSync('RoomId');

            if (song && song.songmid && roomId) {
                console.log(roomId);
                wx.request({
                    url: 'http://localhost:3000/RoomAddSong',
                    method: 'POST',  
                    header: {  
                        'content-type': 'application/json',  
                        'Authorization': wx.getStorageSync('usertoken')
                    },  
                    data: {
                        sid: song.songmid,
                        rid: roomId,
                        songName: song.songName,
                        songAuthor: song.artist
                    },
                    success(res) {  
                        console.log('正在添加歌曲');
                        wx.showToast({
                            title: '房间添加歌曲成功',
                        });
                        if (res.statusCode === 202) {  
                            console.log('添加歌曲成功', res.data);  
                        } else if (res.statusCode === 252) {
                            console.error('添加歌曲失败', res.data);  
                        } else if (res.data.code === 401) {
                            utils.userlogin();
                        }
                    },  
                    fail(err) {  
                        console.error('请求失败', err);  
                    }  
                });
            } else {
                console.error('song 或 roomId 缺失');
            }
        } else {
            console.log("歌曲已存在歌单中");
        }
    };

    this.setData({
        songs: this.data.songs
    });
}

,


  // ChangeLoveList:function(e) {
  //   let id = e.currentTarget.dataset.sId;
  //   utils.LovelistChange(id);
  //   this.triggerEvent('LovelistSongChange', { sId: id });
  //   console.log("改变收藏夹成功");
  //   this.setData({
  //     songs:this.data.songs
  //   })
  // },
});
